package test.linecounter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LineCounter
{
	private final String BLANK = "^[\\s]*$";
	private final String LINE_COMMENT = "^[\\s]*\\/\\/.*";
	private final String LINE_COMMENT2 = "^[\\s]*\\/\\*.*\\*\\/[\\s]*$";
	private final String BLOCK_COMMENT_START = "^[\\s]*\\/\\*.*";
	private final String BLOCK_COMMENT_END = ".*\\*\\/$";

//	private final File SRC_ROOT = new File(
//			"D:\\Workspace\\oubound-vcc-2.3");
	private final File SRC_ROOT = new File(
	"C:\\Java\\eclipse\\workspace\\outbound");
	
	private final String COUNT_TYPE = ".java";
	private int commentLine = 0;
	private int blankLine = 0;
	private int validLine = 0;

	private BufferedReader bf;
	private String line;

	public static void main(String[] args)
	{
		try
		{
			new LineCounter().launch();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (NullPointerException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	private void launch() throws FileNotFoundException, NullPointerException,
			IOException
	{
		counterWithPath(SRC_ROOT);
		System.out.println("count type: " + COUNT_TYPE);
		System.out.println("blankLine: " + blankLine);
		System.out.println("commentLine: " + commentLine);
		System.out.println("validLine: " + validLine);

	}

	private void counterWithPath(File path) throws FileNotFoundException,
			NullPointerException, IOException
	{
		if (path.isFile() == true && path.toString().endsWith(COUNT_TYPE))
		{
			readFile(path);
		}
		else
			if (path.isDirectory())
			{
				File[] files = path.listFiles();
				for (int i = 0; i < files.length; i++)
				{
					counterWithPath(files[i]);
				}
			}
	}

	private void readFile(File path) throws FileNotFoundException,
			NullPointerException, IOException
	{
		bf = new BufferedReader(new FileReader(path));
		boolean inCommentBlock = false;
		while ((line = bf.readLine()) != null)
		{
			if (inCommentBlock == true
					&& !Pattern.matches(BLOCK_COMMENT_END, line))
			{
				commentLine++;
			}
			else
				if (Pattern.matches(LINE_COMMENT, line)
						|| Pattern.matches(LINE_COMMENT2, line))
				{
					commentLine++;
				}
				else
					if (inCommentBlock == true
							&& Pattern.matches(BLOCK_COMMENT_END, line))
					{
						commentLine++;
						inCommentBlock = false;
					}
					else
						if (Pattern.matches(BLOCK_COMMENT_START, line))
						{
							commentLine++;
							inCommentBlock = true;
						}
						else
							if (Pattern.matches(BLANK, line))
							{
								blankLine++;
							}
							else
							{
								validLine++;
							}
		}

	}
}
